#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
using namespace std;

const int N = 1e6 + 10, INF = 0x3f3f3f3f;

int n;
char op[50010];
string s[50010];

int ans[N], mi;

struct AC {
    char offset = 'a';
    int tr[N][26], fail[N];
    vector<int> eds[N];
    int idx;

    AC() {
        memset(tr, 0, sizeof tr);
        memset(fail, 0, sizeof fail);
        for (int i = 0;i < N;i++) eds[i].clear();
        idx = 0;
    }

    void insert(const string& s, int id)
    {
        int p = 0;
        for (char it : s) {
            int c = it - offset;
            if (tr[p][c] == 0) tr[p][c] = ++idx;
            p = tr[p][c];
        }
        eds[p].push_back(id);
    }

    void setfail()
    {
        queue<int> q;
        for (int i = 0;i < 26;i++) if (tr[0][i]) { q.push(tr[0][i]); }
        while (!q.empty()) {
            int now = q.front();q.pop();
            for (int i = 0;i < 26;i++)
                if (tr[now][i]) {
                    fail[tr[now][i]] = tr[fail[now]][i];
                    q.push(tr[now][i]);
                } else tr[now][i] = tr[fail[now]][i];
        }
    }

    void query(string& s, int l, int r, int op)
    {
        int p = 0;
        vector<int> st(idx + 1);
        for (char it : s) {
            int ch = it - offset;
            p = tr[p][ch];
            for (int k = p;k > 0 && !st[k];k = fail[k]) {
                for (int x : eds[k]) if (x >= l && x <= r)
                    if (op == 0)  mi = min(mi, x);
                    else  ans[x]++;
                st[k] = 1;
            }
        }
    }
}que, del;

void solve()
{
    cin >> n;
    for (int i = 1;i <= n;i++) {
        cin >> op[i] >> s[i];
        if (op[i] == 'Q') que.insert(s[i], i);
        if (op[i] == 'D') del.insert(s[i], i);
    }

    que.setfail();
    del.setfail();

    for (int i = 1;i <= n;i++) {
        if (op[i] != 'I') continue;
        mi = INF;
        del.query(s[i], i, n, 0);
        que.query(s[i], i, mi - 1, 1);
    }

    for (int i = 1;i <= n;i++) if (op[i] == 'Q')
        cout << ans[i] << '\n';
}

signed main()
{
    // ios::sync_with_stdio(0);
    // cin.tie(0);cout.tie(0);
#define ONLINE_JUDGE
#ifndef ONLINE_JUDGE
    std::istringstream in(R"()");
    std::cin.rdbuf(in.rdbuf());
#endif
    int T = 1;
    //cin>>T;
    for (int i = 1;i <= T;i++) {
        solve();
    }
}